package com.livegoods.service.impl;

import com.livegoods.pojo.Comment;
import com.livegoods.pojo.LivegoodsResult;
import com.livegoods.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {



    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public LivegoodsResult selectCommontPageDataById(String id, int page) {

        Criteria criteria = Criteria.where("houseId").is(id);

        int size = 15;
        Query query = new Query(criteria);
        query.with(PageRequest.of(page, size));

        //查询结果
        List<Comment> comments = mongoTemplate.find(query, Comment.class);

        for (Comment comment : comments) {
            String username = comment.getUsername();
            username = username.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
            comment.setUsername(username);
        }

        //总数
        GroupOperation totalOperation = Aggregation.group().count().as("total");


        TypedAggregation<Comment> typedAggregation = TypedAggregation.newAggregation(Comment.class, totalOperation);

        //查询总记录
        AggregationResults<Map> aggregate = mongoTemplate.aggregate(typedAggregation, Map.class);

        Map uniqueMappedResult = aggregate.getUniqueMappedResult();
        int total = (int) uniqueMappedResult.get("total");

        LivegoodsResult livegoodsResult = LivegoodsResult.ok(comments);

        //计算总页数
        int totalPage = total % size == 0 ? total / size : total / size + 1;

        if(page<totalPage-1){
            livegoodsResult.setHasMore(true);
        }else{
            livegoodsResult.setHasMore(false);
        }
        return livegoodsResult;
    }
}
